package frog.lazy.framework.http.factory;

import cn.hutool.core.util.NumberUtil;
import frog.lazy.framework.core.base.IBaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * 枚举类转换
 * 传值
 */
public class StringToEnumConverterFactory implements ConverterFactory<String, IBaseEnum > {
    private static final Map<Class, Converter> converterMap = new WeakHashMap<>();
    @Override
    public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter result = converterMap.get(targetType);
        if(result == null) {
            result = new IntegerStrToEnum(targetType);
            converterMap.put(targetType, result);
        }
        return result;
    }

    class IntegerStrToEnum<T extends Enum> implements Converter<String, T> {
        private final Class<T> enumType;
        private Map<String, T> enumMap = new HashMap<>();

        public IntegerStrToEnum(Class<T> enumType) {
            this.enumType = enumType;
            T[] enums = enumType.getEnumConstants();
            for(T e : enums) {
                if(e instanceof Enum) {
                    enumMap.put(((IBaseEnum)e).getValue() + "", e);
                }

            }
        }


        @Override
        public T convert(String source) {
            if(NumberUtil.isNumber(source)){
                T result = enumMap.get(source);
                if(result == null) {
                    throw new IllegalArgumentException("No element matches " + source);
                }
                return result;
            }
            return (T) Enum.valueOf(this.enumType, source.trim());
        }
    }

}
